const router = require('koa-router')()
const { query } = require('../plugin/db.js')
const path = require('path')
const fs = require('fs')
const axios = require('axios')
const mydata = fs.readFileSync(path.join(__dirname, '../sql/clockin_data.sql'), 'binary')
router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/app/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.post('/app/json', async (ctx, next) => {
  console.log(ctx.request.body);
  const { username } = ctx.request.body
  const sql = `INSERT INTO clockin_data(name, clocktime) VALUES('${username}', NOW())`
  await query(mydata.trim())
  const result = await query(sql)
  ctx.body = {
    title: result
  }
})

router.post('/app/UserClockIn', async (ctx, next) => {
  const { username } = ctx.request.body
  const sql = `SELECT * FROM clockin_data WHERE NAME='${username}'`
  const res = await query(sql)
  console.log(res);
  ctx.body = {
    data: res
  }
})

router.get('/app/login', async (ctx, next) => {
  const { code } = ctx.query
  const { data } = await axios.get(`https://api.weixin.qq.com/sns/jscode2session?appid=wx65200f7255be3193&secret=8dc0fca3e54294cc42fdc79606647e95&js_code=${code}&grant_type=authorization_code`)
  const sql = `SELECT * FROM clockin_data WHERE openid='${data.openid}'`
  const createSql = `INSERT INTO clockin_data(openid) VALUES('${data.openid}')`
  const res = await query(sql)
  console.log(res);
  if (res.length) {
    ctx.body = {
      data: '123'
    }
  } else {
    await query(createSql)
    ctx.body = {
      data: '创建成功'
    }
  }
  console.log(data);
})

router.post('/getApply', async (ctx, next) => {
  const { username } = ctx.request.body
  const sql = `SELECT * FROM clockin_data WHERE NAME='${username}'`
  const res = await query(sql)
  console.log(res);
  ctx.body = {
    data: res
  }
})

module.exports = router
